<template>
  <div class="register-container">
    <div class="register-background">
      <div class="register-diagonal"></div>
    </div>
    <div class="register-form-container">
      <div class="register-header">
        <h1>注册MES系统账号</h1>
        <h2>Create Manufacturing Execution System Account</h2>
      </div>

      <el-form
        class="register-form"
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            prefix-icon="Lock"
            show-password
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱"
            prefix-icon="Message"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item prop="verificationCode">
          <div class="verification-code">
            <el-input
              v-model="registerForm.verificationCode"
              placeholder="请输入验证码"
              prefix-icon="Key"
              clearable
            ></el-input>
            <el-button
              type="primary"
              plain
              class="send-code-btn"
              @click="sendVerificationCode"
              :disabled="isCountingDown"
            >
              {{ countdown > 0 ? `${countdown}s后重新获取` : "获取验证码" }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item prop="agreement">
          <el-checkbox v-model="registerForm.agreement">
            我已阅读并同意<el-link type="primary" @click="showAgreement"
              >《用户协议》</el-link
            >和<el-link type="primary" @click="showPrivacy"
              >《隐私政策》</el-link
            >
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            class="register-btn"
            @click="handleRegister"
            :loading="loading"
          >
            立即注册
          </el-button>
        </el-form-item>

        <div class="login-prompt">
          已有账号?
          <router-link to="/login" class="login-link">立即登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ArrowLeft,
  User,
  Lock,
  Message,
  Phone,
  Key,
} from "@element-plus/icons-vue";
import { postRegisterApi } from "@/api/Register";
import { SET_TOKEN } from "@/utils/token";

const router = useRouter();

// 注册表单数据
const registerForm = ref({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
  phone: "",
  verificationCode: "",
  agreement: false,
});

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 4, message: "用户名长度不能少于4位", trigger: "blur" },
    { max: 16, message: "用户名长度不能超过16位", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 8, message: "密码长度不能少于8位", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!/[A-Za-z]/.test(value) || !/\d/.test(value)) {
          callback(new Error("密码必须包含字母和数字"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== registerForm.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
    },
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: ["blur", "change"],
    },
  ],
  verificationCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    {
      pattern: /^\d{6}$/,
      message: "验证码为6位数字",
      trigger: ["blur", "change"],
    },
  ],
  agreement: [
    {
      validator: (rule: any, value: boolean, callback: any) => {
        if (!value) {
          callback(new Error("请阅读并同意用户协议和隐私政策"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
};

const loading = ref(false);
const registerFormRef = ref();
const countdown = ref(0);
const isCountingDown = ref(false);

// 发送验证码
const sendVerificationCode = () => {
  if (!registerForm.value.phone) {
    ElMessage.warning("请输入手机号");
    return;
  }

  // 模拟发送验证码
  isCountingDown.value = true;
  countdown.value = 60;

  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isCountingDown.value = false;
    }
  }, 1000);

  ElMessage.success("验证码已发送，请注意查收");
};

// 显示用户协议
const showAgreement = () => {
  ElMessageBox.alert("这里是用户协议内容...", "用户协议", {
    confirmButtonText: "我知道了",
    customClass: "agreement-dialog",
  });
};

// 显示隐私政策
const showPrivacy = () => {
  ElMessageBox.alert("这里是隐私政策内容...", "隐私政策", {
    confirmButtonText: "我知道了",
    customClass: "privacy-dialog",
  });
};

// 处理注册
const handleRegister = () => {
  registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        const res: any = await postRegisterApi({
          username: registerForm.value.username,
          password: registerForm.value.password,
          email: registerForm.value.email,
          mobilePhoneNumber: registerForm.value.phone,
        });
        ElMessage.success("注册成功，即将跳转登录页面");
        setTimeout(() => {
          router.push("/login");
        }, 1000);
      } catch (err: any) {
        console.log(err);
        ElMessage.error("请检查输入信息");
      } finally {
        loading.value = false;
      }
    }
  });
};
</script>

<style scoped>
.register-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

.register-background {
  flex: 1;
  background: url("https://example.com/mes-background.jpg") no-repeat center
    center;
  background-size: cover;
  position: relative;
}

.register-diagonal {
  position: absolute;
  top: 0;
  right: 0;
  width: 200%;
  height: 200%;
  background: linear-gradient(
    to bottom left,
    transparent 0%,
    transparent 50%,
    rgba(27, 154, 238, 0.8) 50%,
    rgba(27, 154, 238, 0.8) 100%
  );
  transform: translateX(50%) translateY(-50%) rotate(45deg);
  transform-origin: center center;
  z-index: 1;
}

.register-form-container {
  width: 550px;
  background: white;
  padding: 60px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: -5px 0 15px rgba(0, 0, 0, 0.1);
  z-index: 2;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h1 {
  font-size: 24px;
  color: #1b9aee;
  margin-bottom: 10px;
}

.register-header h2 {
  font-size: 16px;
  color: #666;
  font-weight: normal;
}

.register-form {
  width: 100%;
}

/* 输入框样式 */
.register-form :deep(.el-input__wrapper) {
  height: 48px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s;
}

.register-form :deep(.el-input__wrapper.is-focus) {
  border-color: #1b9aee;
  box-shadow: 0 0 0 2px rgba(23, 92, 180, 0.2);
}

.register-form :deep(.el-input__inner) {
  font-size: 14px;
  color: #333;
}

.register-form :deep(.el-input__prefix) {
  color: #1b9aee;
  margin-left: 10px;
}

/* 验证码输入区域 */
.verification-code {
  display: flex;

  gap: 10px;
}

.send-code-btn {
  width: 140px;
  margin-top: 10px;
  flex-shrink: 0;
  border-color: #1b9aee;
  color: #1b9aee;
}

.send-code-btn:hover {
  background-color: rgba(23, 92, 180, 0.1);
}

.send-code-btn:disabled {
  color: #999;
  border-color: #e0e0e0;
  background-color: #f5f5f5;
}

/* 注册按钮 */
.register-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  background-color: #1b9aee;
  border-color: #1b9aee;
  border-radius: 6px;
  transition: all 0.3s;
}

.register-btn:hover {
  background-color: #1a6fd8;
  border-color: #1a6fd8;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(23, 92, 180, 0.2);
}

.register-btn:active {
  transform: translateY(0);
}

/* 用户协议 */
.register-form :deep(.el-checkbox__label) {
  font-size: 14px;
}

.register-form :deep(.el-link) {
  vertical-align: baseline;
}

/* 登录提示 */
.login-prompt {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

.login-link {
  color: #1b9aee;
  text-decoration: none;
  margin-left: 5px;
}

.login-link:hover {
  text-decoration: underline;
}

/* 页脚 */
.register-footer {
  margin-top: 30px;
  text-align: center;
}

.copyright {
  color: #999;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    flex-direction: column;
  }

  .register-background {
    display: none;
  }

  .register-form-container {
    width: 100%;
    padding: 40px 20px;
  }

  .verification-code {
    flex-direction: column;
  }

  .send-code-btn {
    width: 100%;
  }
}

/* 协议弹窗样式 */
:deep(.agreement-dialog),
:deep(.privacy-dialog) {
  max-width: 80%;
  max-height: 80vh;
  overflow-y: auto;
}

:deep(.agreement-dialog .el-message-box__content),
:deep(.privacy-dialog .el-message-box__content) {
  padding: 20px;
  line-height: 1.6;
  color: #333;
}
</style>
